package app;

import java.util.Dictionary;

import org.w3c.dom.Element;

import utils.*;

import com.StarMicronics.StarIOSDK.*;

import android.content.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class ServerView implements HttpItemListener, DataSourceChangeNotificationListener {
	private ListView table;
	private EditText server_name;
	private EditText server_address;
	private Button english_btn;
	private Button spanish_btn;
	private ImageView switch_iamge;
	private Button test;
	private Button add_server;
	private MyAdapter adapter;
	private View view;
	
	
	private HttpQueue normalQuene;
	private WaittingAlertView waittingAlertView;
	
	public void bind() {
	    //[list setupController:self.table data:[LoginServer sharedInstance] reuse:@"loginServers"];
	    //[self.server_name becomeFirstResponder];
	    //LoginServerBG* bg = [[LoginServerBG alloc] initWithFrame:CGRectZero];
	    //[list setBGWithColor1:[UIColor colorWithARGB:0xFFF7F7F7] color2:[UIColor colorWithARGB:0xFFC4CCD6] height:38 bg:bg];
	    //[bg release];
	}
	
	public ServerView() {
		normalQuene = new HttpQueue();
		view = AppDelegate.sharedInstance().activity.getLayoutInflater().inflate(R.layout.server_view, null);
		table = (ListView) view.findViewById(R.id.table_server);
		server_name = (EditText) view.findViewById(R.id.name);
		server_address = (EditText) view.findViewById(R.id.url);
		english_btn = (Button) view.findViewById(R.id.lan_us);
		spanish_btn = (Button) view.findViewById(R.id.lan_es);
		switch_iamge = (ImageView) view.findViewById(R.id.switch_image);
		
		test = (Button) view.findViewById(R.id.test);
		add_server = (Button) view.findViewById(R.id.add_server);
		
		english_btn.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		english();
        	}
		});
		spanish_btn.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		spanish();
        	}
		});
		test.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		test();
        	}
		});
		add_server.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		add_server();
        	}
		});
		view.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		cancel();
        	}
		});
		adapter = new MyAdapter(AppDelegate.sharedInstance().activity);
		table.setAdapter(adapter);
		table.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
	        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {  
	              
	            adapter.setSelectItem(arg2);  
	            adapter.notifyDataSetInvalidated();  
	        }
		});
		AppDelegate.sharedInstance().addNotificationListener(DataSourceChangeNotificationListener.class, this);
		
		updateLanguage();
		
		if (FilePack.currentLanguage() == R.raw.c_en_us) {
			english_btn.setEnabled(false);
			spanish_btn.setEnabled(true);
			english_btn.setTextColor(0xFFFFFFFF);
			spanish_btn.setTextColor(0xFFA5A5A5);
			switch_iamge.setImageDrawable(view.getResources().getDrawable(R.drawable.switch1));
		} else {
			spanish_btn.setEnabled(false);
			english_btn.setEnabled(true);
			spanish_btn.setTextColor(0xFFFFFFFF);
			english_btn.setTextColor(0xFFA5A5A5);
			switch_iamge.setImageDrawable(view.getResources().getDrawable(R.drawable.switch2));
		}
	}

	private void english() {
		english_btn.setEnabled(false);
		spanish_btn.setEnabled(true);
		english_btn.setTextColor(0xFFFFFFFF);
		spanish_btn.setTextColor(0xFFA5A5A5);
		switch_iamge.setImageDrawable(view.getResources().getDrawable(R.drawable.switch1));
		FilePack.setCurrentlanguage(R.raw.c_en_us);
	}
	private void spanish() {
		spanish_btn.setEnabled(false);
		english_btn.setEnabled(true);
		spanish_btn.setTextColor(0xFFFFFFFF);
		english_btn.setTextColor(0xFFA5A5A5);
		switch_iamge.setImageDrawable(view.getResources().getDrawable(R.drawable.switch2));
		FilePack.setCurrentlanguage(R.raw.c_es_mx);
	}
	private void test() {
		String testUrl = server_address.getText().toString();
		if (testUrl != null && testUrl.length() > 0) {
			String api = testUrl + "/paperlessapi.asmx/serverConnectionCheck?&Language=" + FilePack.currentLanguageString() + "&sAddress=1";
			
			normalQuene.get(api, this, null, true);
			waittingAlertView = WaittingAlertView.createWaittingAlertView();
			waittingAlertView.setLoadingText(FilePack.getStringByID(STRING_ID.STR_PLEASE_WAIT));
			waittingAlertView.show();
		}
	}
	private void add_server() {
		String testUrl = server_address.getText().toString();
		String testName = server_name.getText().toString();
		if (testUrl != null && testName != null && testUrl.length() > 0 && testName.length() > 0) {
			LoginServer.sharedInstance().addServerWithName(testName, testUrl);
			adapter.notifyDataSetInvalidated();
		}
	}
	private void cancel() {
		AppDelegate.sharedInstance().removeNotificationListener(DataSourceChangeNotificationListener.class, this);
		AppDelegate.sharedInstance().layout.removeView(view);
	}

	public void reqeuestFinished(byte[] byteArray, Element xml,
			boolean successfull, Object param) {
		if (successfull) {
			if (XMLReader.getIntForKey(xml, "ret", 0) == 1) {
				waittingAlertView.setTitle(FilePack.getStringByID(STRING_ID.STR_SERVER_AVALIABLE));
			} else {
				waittingAlertView.setTitle(XMLReader.getStringForKey(xml, "error", FilePack.getStringByID(STRING_ID.STR_SERVER_NOT_AVALIABLE)));
			}
		} else {
			waittingAlertView.setTitle(FilePack.getStringByID(STRING_ID.STR_SERVER_NOT_AVALIABLE));
		}
		waittingAlertView = null;
	}
	
	private final class ViewHolder {  
        private TextView nameText;
        private TextView urlText;
        private Button cancelButton;
        
    }
	
	private final class MyAdapter extends BaseAdapter {  
        private LayoutInflater mInflater;  
        public MyAdapter(Context context) {  
            this.mInflater = LayoutInflater.from(context);  
        }  
        public int getCount() {  
            // TODO Auto-generated method stub  
            return LoginServer.sharedInstance().data.size();
        }  
        public Object getItem(int arg0) {  
            // TODO Auto-generated method stub  
            return LoginServer.sharedInstance().data.elementAt(arg0);  
        }  
        public long getItemId(int arg0) {  
            // TODO Auto-generated method stub  
            return arg0;  
        }  
        public View getView(int position, View convertView, ViewGroup parent) {  
            ViewHolder holder = null;  
            if (convertView == null) {  
                holder = new ViewHolder();  
                convertView = mInflater.inflate(R.layout.server_cell, null);  
                holder.nameText = (TextView) convertView.findViewById(R.id.server_cell_name);  
                holder.urlText = (TextView) convertView.findViewById(R.id.server_cell_server);  
                holder.cancelButton = (Button) convertView.findViewById(R.id.server_cell_delete);
                holder.cancelButton.setOnClickListener(new OnClickListener(){
                	public void onClick(View v) {
                		delete();
                	}
                });
                convertView.setTag(holder);
            } else {  
                holder = (ViewHolder) convertView.getTag();  
            }
            
            holder.cancelButton.setText(FilePack.getStringByID(STRING_ID.STR_DELETE));
            
            Dictionary<String, String> dic = LoginServer.sharedInstance().data.elementAt(position);
            holder.nameText.setText(dic.get("name"));
            holder.urlText.setText(dic.get("url"));
            holder.cancelButton.setVisibility(position == selectItem?View.VISIBLE:View.INVISIBLE);
            if (dic.get("changable") == null) {
            	holder.cancelButton.setVisibility(View.INVISIBLE);
            }
            return convertView;  
        }
        private void delete() {
        	LoginServer.sharedInstance().removeServerWithIndex(selectItem);
        	selectItem = -1;
        	this.notifyDataSetInvalidated();
        }

        public  void setSelectItem(int selectItem) {  
             this.selectItem = selectItem;  
        }  
        private int  selectItem=-1;  
    }

	public void notification(Class<?> clss, Object object, Object userInfo) {
		// TODO Auto-generated method stub
		if (clss == DataSourceChangeNotificationListener.class) {
			if (object == LoginServer.sharedInstance()) {
	            adapter.notifyDataSetInvalidated();
			}
		} else if (clss == MultiLanguageChangeNotificationListener.class) {
			updateLanguage();
		}
	}
	
	private void updateLanguage() {
		server_name.setHint(FilePack.getStringByID(STRING_ID.STR_SERVER_NAME));
		server_address.setHint(FilePack.getStringByID(STRING_ID.STR_SERVER_ADDRESS));
		english_btn.setText(FilePack.getStringByID(STRING_ID.STR_ENGLISH));
		spanish_btn.setText(FilePack.getStringByID(STRING_ID.STR_SPANISH));
		test.setText(FilePack.getStringByID(STRING_ID.STR_TEST));
		add_server.setText(FilePack.getStringByID(STRING_ID.STR_ADD_SERVER));
        adapter.notifyDataSetInvalidated();
	}
	
	public void addToWindow() {
		AppDelegate.sharedInstance().layout.addView(view);
		AppDelegate.sharedInstance().addNotificationListener(MultiLanguageChangeNotificationListener.class, this);
		updateLanguage();
	}
	
	public void remove() {
		AppDelegate.sharedInstance().layout.removeView(view);
		AppDelegate.sharedInstance().removeNotificationListener(MultiLanguageChangeNotificationListener.class, this);
	}
}
